add_executable(DecafLangCompiler
        main.cpp
        ASTVisitor.h
        ASTVisitor.cpp
)

# Path to test.decaf and test.ll in src/
set(DECAF_TEST_FILE "${CMAKE_SOURCE_DIR}/src/test.decaf")
set(DECAF_LL_FILE "${CMAKE_SOURCE_DIR}/src/test.ll")

# Generate test.ll from test.decaf
add_custom_command(
        OUTPUT ${DECAF_LL_FILE}
        COMMAND DecafLangCompiler ${DECAF_TEST_FILE} ${DECAF_LL_FILE}
        DEPENDS DecafLangCompiler ${DECAF_TEST_FILE}
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
        COMMENT "Generating LLVM IR from test.decaf"
)

add_custom_target(build_ll
        DEPENDS ${DECAF_LL_FILE}
)

# Run test.ll with lli
find_program(LLI_EXECUTABLE NAMES lli PATHS /opt/homebrew/opt/llvm@17/bin NO_DEFAULT_PATH)
if(NOT LLI_EXECUTABLE)
    find_program(LLI_EXECUTABLE NAMES lli)
endif()

add_custom_target(run_lli
        COMMAND ${LLI_EXECUTABLE} ${DECAF_LL_FILE}
        DEPENDS build_ll
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/src
        COMMENT "Running test.ll with lli"
)

# Compile test.ll to decafprog with -O3
set(LLVM_CLANG_EXECUTABLE "/opt/homebrew/opt/llvm@17/bin/clang")
add_custom_command(
        OUTPUT ${CMAKE_BINARY_DIR}/decafprog
        COMMAND ${LLVM_CLANG_EXECUTABLE} -O3 ${DECAF_LL_FILE} -o decafprog
        DEPENDS ${DECAF_LL_FILE}
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
        COMMENT "Compiling test.ll to optimized decafprog"
)

add_custom_target(build_and_optimize
        DEPENDS ${CMAKE_BINARY_DIR}/decafprog
)

add_custom_target(run_native
        COMMAND ${CMAKE_BINARY_DIR}/decafprog
        DEPENDS build_and_optimize
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
        COMMENT "Running decafprog"
)

# Add the generated ANTLR sources
target_sources(DecafLangCompiler PRIVATE
        ${GENERATED_ANTLR_DIR}/DecafLangLexer.cpp
        ${GENERATED_ANTLR_DIR}/DecafLangParser.cpp
        ${GENERATED_ANTLR_DIR}/DecafLangBaseVisitor.cpp
        ${GENERATED_ANTLR_DIR}/DecafLangVisitor.cpp
)

# Add include directories
target_include_directories(DecafLangCompiler PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}
        ${GENERATED_ANTLR_DIR}
        /opt/homebrew/opt/antlr4-cpp-runtime/include
        /opt/homebrew/opt/antlr4-cpp-runtime/include/antlr4-runtime
        /opt/homebrew/opt/llvm@17/include
)

# Link libraries
target_link_libraries(DecafLangCompiler PRIVATE
        antlr4-runtime
        ${LLVM_LIBS}
)

add_dependencies(DecafLangCompiler antlr_generate_${ANTLR_GRAMMAR_NAME})
